import React from 'react';
import TodoItem from './TodoItem';
import './index.styl';

class TodoList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      inputValue: ''
    }
    // 注册事件
    this.handleChange = this.handleChange.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleDelete = this.handleDelete.bind(this);
  }

  handleChange(e) {
    this.setState({
      inputValue: e.target.value
    });
  }

  handleBtnClick() {
    const value = this.state.inputValue;
    if(!value) {
      alert('请输入信息');
      return false;
    }
    this.setState({
      list: [...this.state.list, value],
      inputValue : ''
    });
  }

  handleDelete(index) {
    // 修改 拷贝副本
    const list = this.state.list.filter((item, key) => {
      return key !== index;
    });
    this.setState({
      list: list 
    })
  }

  getTodoItem() {
    return (
      this.state.list.map((item, key) => {
        return <TodoItem 
                content={{item: item, key: key}} 
                key={key} 
                delete={this.handleDelete}
                />
      })
    );
  }

  render () {
    return(
      <div className="App">
        <div className='app-title'>
            TodoList
        </div>
        <div className='input-area'>
          <input 
            value={this.state.inputValue} 
            onChange={this.handleChange}
          />
          <button onClick={this.handleBtnClick}>add</button>
        </div>
        <div className='data-list'>
          {this.getTodoItem()}
        </div>
      </div>
    );
  }
}

export default TodoList;
